import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

// SMSSender
// The purpose of this class is to send text messages to a specified recipient.
// Each instance represents an email account on an SMTP server; technically,
// this class can send an email to any email address.
public class SMSSender {
	String server;
	String user;
	String pw;
	
	public SMSSender(String SMTPServer, String username, String password) {
		server = SMTPServer;
		user = username;
		pw = password;
	}
	
	/**
	 * Sends a text message to the specified recipient.
	 * @param recipient: the email address of the message's recipient.
	 * @param messageString: the message to send.
	 * This was adapted from the code in Sender.java
	 */
	public synchronized void sendTextMessage(String recipient, String messageString) {
		//bugfix: synchronize for critical section
		try {
			Properties props = System.getProperties();
			
		    props.put("mail.smtp.starttls.enable", "true");
		    props.put("mail.smtp.host", server);
		    props.put("mail.smtp.user", user);
		    props.put("mail.smtp.password", pw);
		    props.put("mail.smtp.port", "587");
		    props.put("mail.smtp.auth", "true");
		 
		    String[] to = {recipient}; 
		 
		    Session session = Session.getDefaultInstance(props, null);
		    MimeMessage message = new MimeMessage(session);
		    message.setFrom(new InternetAddress(user));
		 
		    InternetAddress[] toAddress = new InternetAddress[to.length];
		 
		    // To get the array of addresses
		    for( int i=0; i < to.length; i++ ) { // changed from a while loop
		        toAddress[i] = new InternetAddress(to[i]);
		    }
		    System.out.println(Message.RecipientType.TO + " " + recipient);
		 
		    for( int i=0; i < toAddress.length; i++) { // changed from a while loop
		        message.addRecipient(Message.RecipientType.TO, toAddress[i]);
		    }
		    
		    // If we want to include timestamps in the message we can do so here.
		    // Calendar cal = Calendar.getInstance();
		    // SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_NOW);
		    // String timestamp = sdf.format(cal.getTime());
		    
		    message.setSubject("Home Automation!");
		    message.setText(messageString);
	
		    Transport transport = session.getTransport("smtps");
		    transport.connect(server, user, pw);
		    transport.sendMessage(message, message.getAllRecipients());
		    transport.close();
		} catch (Exception e) {
			// TODO: We should handle exceptions here eventually.... 
		}		
	}

}
